package com.wtoip.core.utils;

import java.io.IOException;
import java.io.Serializable;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtil implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private static ObjectMapper mapper = new ObjectMapper();
	
	/**
	 * 将实体对象转为JSON字符串
	 * @param object
	 * @return
	 */
	public static String bean2Json(Object object) {
		if(null == object) return null;
		
		try {
			return mapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * JSON字符串转为实体对象
	 * @param str
	 * @param clazz
	 * @return
	 */
	public static <T> T json2Bean(String str, Class<T> clazz) {
		if(null == str || "".equals(str.trim())) return null;
		
		try {
			return mapper.readValue(str, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
